/*
* Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "Node.h"
#include "interfaces/c/node.h"
#include <stdexcept>

namespace OHOS {
namespace OHMW {
static std::vector<std::function<void(uint8_t*, uint32_t)>> callbacks;

Node::Node(std::string_view node_path, Type type) {
    node_ = ohmw_node_create(node_path.data(), node_path.size(), static_cast<ohmw_node_type>(type));
    if (node_ == nullptr) {
        throw std::runtime_error("failed to create node: " + std::string(node_path.data(), node_path.size()));
    }
}

Node::~Node() {
    if (node_ != nullptr) {
        ohmw_node_destroy(node_);
    }
}

int32_t Node::Send(std::string_view path, const uint8_t* data, uint32_t len) {
    if (node_ == nullptr) {
        return -1;
    }
    return ohmw_node_send(node_, path.data(), path.size(), data, len);
}

int32_t Node::Recv(std::string_view path, uint8_t* data, uint32_t *len, uint32_t timeout) {
    if (node_ == nullptr) {
        return -1;
    }
    return ohmw_node_recv(node_, path.data(), path.size(), data, len, timeout);
}

static void OnRecvHandler(uint8_t *data, uint32_t len, void *user_data) {
    size_t callback_id = reinterpret_cast<size_t>(user_data);
    callbacks[callback_id](data, len);
}

int32_t Node::OnRecv(std::string_view path, std::function<void(uint8_t*, uint32_t)> callback) {
    if (node_ == nullptr) {
        return -1;
    }
    callbacks.push_back(callback);
    void *callback_id = reinterpret_cast<void *>(callbacks.size() - 1);
    return ohmw_node_on_recv(node_, path.data(), path.size(), OnRecvHandler, callback_id);
}
}
}
